#include <cstdio>//uncle-lu
#include <algorithm>
template<class T>void read(T &x)
{
	x=0;int f=0;char ch=getchar();
	while(ch<'0'||ch>'9') { f|=(ch=='-'); ch=getchar(); }
	while(ch<='9'&&ch>='0') { x=(x<<1)+(x<<3)+(ch^48); ch=getchar(); }
	x = f ? -x : x;
	return ;
}

const int INF = 1e6 + 10;

struct answer{
	int in, out;
	long long int vale;
};
answer ans[INF];
long long int vale[INF];
int in[INF], cnt_in;
int out[INF], cnt_out;
int n, m, cnt_ans;

int main()
{
	int x, y;
	long long val;
	read(n); read(m);
	for(int i=1; i<=m; ++i)
	{
		read(x);read(y);read(val);
		vale[x]-=val; vale[y]+=val;
	}

	for(int i=1;i<=n;++i)
	{
		if(vale[i]>0)
			in[++cnt_in] = i;
		else if(vale[i]<0)
			out[++cnt_out] = i;

		vale[i] = vale[i] < 0 ? -vale[i] : vale[i];
	}
	
	int iter_in = 1, iter_out = 1;
	while(iter_in <= cnt_in && iter_out <= cnt_out)
	{
		long long int v = std::min(vale[in[iter_in]], vale[out[iter_out]]);
		ans[++cnt_ans] = (answer){out[iter_out], in[iter_in], v};
		vale[in[iter_in]] -= v;
		vale[out[iter_out]] -= v;
		if(vale[in[iter_in]] == 0) iter_in ++;
		if(vale[out[iter_out]] == 0) iter_out ++;
	}

	printf("%d\n",cnt_ans);
	for(int i=1; i<=cnt_ans; i++)
	{
		printf("%d %d %lld\n",ans[i].in, ans[i].out, ans[i].vale);
	}

	return 0;
}
